/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.wisnu.spms.service.dao.impl;

import com.wisnu.spms.service.dao.DbPaymentDao;
import com.wisnu.spms.service.entity.DbBilling;
import com.wisnu.spms.service.entity.DbCashlog;
import com.wisnu.spms.service.entity.DbPayment;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public class DbPaymentDaoImpl extends HibernateDaoSupport implements DbPaymentDao {

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public void insertPayment(DbPayment payment, DbCashlog dbCashlog) throws Exception {
         try {
            getHibernateTemplate().save(payment);
            getHibernateTemplate().save(dbCashlog);
        } catch (DataAccessException t) {
            throw new Exception(t.getMessage());
        }
    }

    @Override
    @Transactional(readOnly = true)
    public List<DbPayment> getPayments() throws Exception {
        try {
            return getHibernateTemplate().loadAll(DbPayment.class);
        } catch (DataAccessException t) {
            throw new Exception(t.getMessage());
        }
    }

    @Override
    @Transactional(readOnly = true)
    public List<DbPayment> getPaymentByBilling(final DbBilling billing) throws Exception {
        try {
            Object o = getHibernateTemplate().execute(new HibernateCallback() {

                @Override
                public Object doInHibernate(Session session) throws HibernateException, SQLException {
                    return session.createQuery("select a from DbPayment a where a.dbBilling = :id")
                            .setParameter("id", billing).list();
                }
            });
            if (o == null) {
                throw new Exception("Student with ID " + billing + " do not found");
            } else {
                return (List<DbPayment>) o;
            }
        } catch (Exception t) {
            throw new Exception(t.getMessage());
        }
    }

}
